<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

/**
 * App\Models\ArticleCategory
 * @mixin \Eloquent
 */
class ArticleCategory extends Model
{
    const STATE_DISABLED = 0;
    const STATE_ENABLED = 1;
    const STATES = [
        self::STATE_DISABLED => '禁用',
        self::STATE_ENABLED => '已启用',
    ];

    protected $fillable = [
        'parent_id',
        'parent_chain',
        'name',
        'sort',
        'state',
    ];

    public function parent()
    {
        return $this->belongsTo(static::class, 'parent_id');
    }

    public static function getParentChain($id)
    {
        $model = self::find($id);
        if($model->parent_id == 0) {
            $parentChain = $model->name;
        } else {
            $parentChain = $model->parent_chain . '/' .$model->name;
        }
        return $parentChain;
    }

    public static function getChains()
    {
        $arr = [];
        $results = static::query()->get();
        foreach ($results as $result) {
            if($result->parent_id == 0) {
                $parentChain = $result->name;
            } else {
                $parentChain = $result->parent_chain . '/' .$result->name;
            }
            $arr[$result->id] = $parentChain;
        }
        return $arr;
    }

    public static function getParents($parentId = 0) {
        $query = static::query();
        if($parentId) {
            $query = $query->where('parent_id', $parentId);
        }
        return $query->pluck('name', 'id')->toArray();
    }

    public static function isRepetition($name, $id = null)
    {
        $result = self::where([
            'name' => $name,
        ]);
        if($id) {
            $result = $result->where('id', '!=', $id);
        }
        return $result->first() ? true : false;
    }
}
